package com.service;

import com.entity.BusinessUtilityBill;
import com.exception.BusinessException;
import com.repository.BusinessUtilityRecordRepository;
import com.repository.BusinessUtilityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BusinessUtilityBillService {

    @Autowired
    private BusinessUtilityRepository businessUtilityRepository;

    @Autowired
    private BusinessUtilityRecordRepository businessUtilityRecordRepository;

    public BusinessUtilityBill save(BusinessUtilityBill businessUtilityBill) {
        Optional<BusinessUtilityBill> byProjectNameAndBillMonth = businessUtilityRepository.findByProjectNameAndBillMonth(businessUtilityBill.getProjectName(), businessUtilityBill.getBillMonth());
        if (businessUtilityBill.getId() == null && byProjectNameAndBillMonth.isPresent()) {
            throw new BusinessException("该项目此月份已经存在");
        }
        businessUtilityBill.setTotalFee(businessUtilityBill.getWaterFee().add(businessUtilityBill.getElectricityFee()));
        return businessUtilityRepository.save(businessUtilityBill);
    }

    public BusinessUtilityBill update(BusinessUtilityBill businessUtilityBill) {
        return businessUtilityRepository.save(businessUtilityBill);
    }

    public void deleteById(Integer id) {
        businessUtilityRecordRepository.deleteAllByUtilityBillId(id);
        businessUtilityRepository.deleteById(id);
    }

    public BusinessUtilityBill findById(Integer id) {
        Optional<BusinessUtilityBill> optional = businessUtilityRepository.findById(id);
        optional.ifPresent(businessUtilityBill -> businessUtilityBill.setFlows(
                businessUtilityRecordRepository.findAllByUtilityBillId(businessUtilityBill.getId())));
        return optional.orElse(null);
    }

    public List<BusinessUtilityBill> findAll() {
        return businessUtilityRepository.findAll();
    }

    public Page<BusinessUtilityBill> findAll(Pageable pageable) {
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(Sort.Direction.DESC, "id"));
        Page<BusinessUtilityBill> page = businessUtilityRepository.findAll(pageable);
        page.forEach(businessUtilityBill ->
                businessUtilityBill.setFlows(businessUtilityRecordRepository.findAllByUtilityBillId(businessUtilityBill.getId())));
        return page;
    }
}